package com.imooc.mq;

import com.imooc.api.mq.DelayConfig_Industry;
import com.imooc.base.BaseInfoProperties;
import com.imooc.pojo.DataDictionary;
import com.imooc.service.DataDictionaryService;
import com.imooc.utils.GsonUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Author Mr.Yang
 * @Date 2024-09-10 10:51
 * @question: 更新字典表的rabbitMQ弱更新的消费者 延迟队列
 */

@Slf4j
@Component
public class RabbitMQDelayConsumer_DataDict extends BaseInfoProperties {

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @RabbitListener(queues = {DelayConfig_Industry.QUEUE_DELAY_REFRESH})
    public void watchQueue(Message message, Channel channel) throws Exception {

        String routingKey = message.getMessageProperties().getReceivedRoutingKey();
        log.info("routingKey = " + routingKey);

        String msg = new String(message.getBody());
        log.info("msg = " + msg);
        log.info("当前时间为：" + LocalDateTime.now());

        /**
         * 是字典表更新的延迟队列则进入
         */
        if (routingKey.equalsIgnoreCase(DelayConfig_Industry.DELAY_REFRESH_DATADICT)) {
            log.info("10秒后监听到延迟队列(字典数据)");

            //从Redis中删除字典key
            redis.del(DATA_DICTIONARY_LIST_TYPECODE);
            //查询全部字典表
            Map<String, List<DataDictionary>> dataDictByTypeCode = dataDictionaryService.getDictList();

            if (!CollectionUtils.isEmpty(dataDictByTypeCode)) {

                for (Map.Entry<String, List<DataDictionary>> entry : dataDictByTypeCode.entrySet()) {
                    //获取键 key
                    String key = entry.getKey();
                    //获取值 value
                    List<DataDictionary> dataDictionaryList = entry.getValue();

                    //设置key 并存入redis
                    String DDKEY_PREFIX = DATA_DICTIONARY_LIST_TYPECODE + ":";
                    String ddkey = DDKEY_PREFIX + key;

                    //设置一级分类到Redis
                    redis.set(ddkey, GsonUtils.object2String(dataDictionaryList));
                }
            }
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
    }


}
